/*
 * Zenlayer.com Inc.
 * Copyright (c) 2014-2020 All Rights Reserved.
 */
package com.shen.core.common;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.EnumTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author yangshen
 * @date 2020-04-17 16:46:01
 * @version $ Id: AutoEnumTypeHandler.java, v 0.1  yangshen Exp $
 */
public class AutoEnumTypeHandler<T> extends BaseTypeHandler<T> {

    private final TypeHandler<T> typeHandler;

    public AutoEnumTypeHandler(Class<T> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
        if (BaseEnum.class.isAssignableFrom(type)) {
            // 如果实现了 BaseCodeEnum 则使用我们自定义的转换器
            Class<? extends TypeHandler> codeEnumTypeHandler = CodeEnumTypeHandler.class;
            typeHandler = typeHandlerRegistry.getInstance(type, codeEnumTypeHandler);
            return;
        }
        // 默认转换器 也可换成 EnumOrdinalTypeHandler
        Class<? extends TypeHandler> defaultEnumTypeHandler = EnumTypeHandler.class;
        typeHandler = typeHandlerRegistry.getInstance(type, defaultEnumTypeHandler);
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        typeHandler.setParameter(ps, i, parameter, jdbcType);
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return typeHandler.getResult(rs, columnName);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return typeHandler.getResult(rs, columnIndex);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return typeHandler.getResult(cs, columnIndex);
    }
}
